import React, { Component } from "react";
import { Text, View, PickerIOS } from "react-native";
import _ from 'lodash';
import { formStore } from "../..";
import styles from './styles';

const PickerItem = PickerIOS.Item;

export default class Options extends Component {
  constructor(props) {
    super(props)
    this.state = {
      value: props.value || '',
      options: [],
      status: 0,
    }
  }
  componentWillReceiveProps(next) {
    this.setState({
      value: next.value,
      options: next.options
    })
  }

  options = (opts) => {
    const _opts = _.cloneDeep(opts.slice());
    _opts.unshift({ label: '请选择', value: '' })
    return _.map(_opts, ({ label, value, fieldKey }, i) => {
      return <PickerItem key={`${fieldKey}_${value}_${i}`} label={label} value={value} />
    })
  }

  onChange = value => {
    this.setState({ value });
  };
  onCancel = () => {
    if (_.isFunction(this.props.onCancel)) {
      this.props.onCancel();
    } else {
      formStore.dismissPickerIOS();
    }
  }
  onOk = () => {
    if (_.isFunction(this.props.onOk)) {
      this.props.onOk(this.state.value);
    } else {
      formStore.setValue(this.props.fieldKey, this.state.value)
      formStore.dismissPickerIOS();
    }
  }
  render() {
    return (
      <View style={styles.optionsWrap}>
        <View style={styles.optionHead}>
          <Text style={styles.headbtn} onPress={this.onCancel}>取消</Text>
          <Text style={styles.headbtn} onPress={this.onOk}>确定</Text>
        </View>
        <PickerIOS
          itemStyle={styles.optionItem}
          selectedValue={this.state.value}
          onValueChange={this.onChange}
          style={styles.optionList}
        >
          {this.options(this.props.options || [])}
        </PickerIOS>

      </View>
    );
  }
}